//
//  ViewController.m
//  test
//
//  Created by Yang,Fei(GR&DD) on 2020/10/15.
//  Copyright © 2020 Yang,Fei. All rights reserved.
//

#import "ViewController.h"
#import <StoreKit/StoreKit.h>
@interface ViewController ()<SKProductsRequestDelegate,SKPaymentTransactionObserver>

@end
@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
 UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"总共免费使用5次，已消耗完" message:@"付费后可无限次使用" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"付费" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//            [IHUtility addWaitingView:@"支付中"];
            //监听购买结果
            [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
            if([SKPaymentQueue canMakePayments]){
                [self requestProductData:@"test_01"];
            }else{
                NSLog(@"不允许程序内付费");
            }
        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        // 弹出对话框
        [self presentViewController:alert animated:true completion:nil];
}
//去苹果服务器请求商品
- (void)requestProductData:(NSString *)type{
    
    NSArray *product = [[NSArray alloc] initWithObjects:type,nil];
    NSSet *nsset = [NSSet setWithArray:product];
    SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:nsset];
    request.delegate = self;
    [request start];
}

//收到产品返回信息
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response{
    
    NSLog(@"--------------收到产品反馈消息---------------------");
    NSArray *product = response.products;
    NSLog(@"productID:%@", response.invalidProductIdentifiers);
    if(product.count==0){
//        [WHToast showMessage:@"查找不到商品信息"  duration:1 finishHandler:^{
//        }];
        NSLog(@"查找不到商品信息");
        return;
    }
//    [IHUtility addWaitingView:@"支付中"];
    SKProduct *p = nil;
    for(SKProduct *pro in product) {
        NSLog(@"%@", [pro description]);
        NSLog(@"%@", [pro localizedTitle]);
        NSLog(@"%@", [pro localizedDescription]);
        NSLog(@"%@", [pro price]);
        NSLog(@"%@", [pro productIdentifier]);
        
        if([pro.productIdentifier isEqualToString: @"com.IntelligentNetwork.QuickIdentificationDiagram.purchase1"]){
            p = pro;
        }
    }
    SKPayment *payment = [SKPayment paymentWithProduct:p];
    NSLog(@"发送购买请求");
    [[SKPaymentQueue defaultQueue] addPayment:payment];
}

//请求失败
- (void)request:(SKRequest *)request didFailWithError:(NSError *)error{
//    [IHUtility removeWaitingView];
//    [WHToast showMessage:@"支付失败"  duration:1 finishHandler:^{
//    }];
    NSLog(@"支付失败");
}

- (void)requestDidFinish:(SKRequest *)request{
//    [IHUtility removeWaitingView];
}

//监听购买结果
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transaction{
//    [IHUtility removeWaitingView];
    for(SKPaymentTransaction *tran in transaction){
        [self verifyPurchaseWithPaymentTransaction:[NSNumber numberWithInt:tran.transactionState]];
        switch(tran.transactionState) {
            case SKPaymentTransactionStatePurchased:{
                [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"buyed"];
                [[SKPaymentQueue defaultQueue] finishTransaction:tran];
            }
                break;
            case SKPaymentTransactionStatePurchasing:
                break;
            case SKPaymentTransactionStateRestored:{
                [[SKPaymentQueue defaultQueue] finishTransaction:tran];
            }
                break;
            case SKPaymentTransactionStateFailed:{
                [[SKPaymentQueue defaultQueue] finishTransaction:tran];
//                [WHToast showMessage:@"购买失败"  duration:1 finishHandler:^{
//                }];
                NSLog(@"购买失败");
            }
                break;
            default:
                break;
        }
    }
}

//交易结束
- (void)completeTransaction:(SKPaymentTransaction *)transaction{
    NSLog(@"交易结束");
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
    
}


- (void)dealloc{
    [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
}

-(void)verifyPurchaseWithPaymentTransaction:(NSNumber*)resultState{
    //从沙盒中获取交易凭证并且拼接成请求体数据
    NSURL *receiptUrl=[[NSBundle mainBundle] appStoreReceiptURL];
    NSData *receiptData=[NSData dataWithContentsOfURL:receiptUrl];
}
@end

